package com.purchase.ml.service.shoppingcart.impl;

import com.purchase.ml.bean.req.shoppingcart.ProductCartReq;
import com.purchase.ml.bean.res.shoppingcart.ShoppingCartRes;
import com.purchase.ml.config.cache.CacheDao;
import com.purchase.ml.consts.CommonConsts;
import com.purchase.ml.entity.acc.SysUser;
import com.purchase.ml.entity.dealer.SysDealer;
import com.purchase.ml.entity.dealer.SysDealerPruduct;
import com.purchase.ml.entity.prod.SysProduct;
import com.purchase.ml.entity.prod.SysProductPic;
import com.purchase.ml.entity.prod.SysProductSku;
import com.purchase.ml.enums.RedisCacheEnum;
import com.purchase.ml.exception.BizException;
import com.purchase.ml.exception.CommonEnum;
import com.purchase.ml.mapper.dealer.DealerProductMapper;
import com.purchase.ml.mapper.dealer.SysDealerMapper;
import com.purchase.ml.mapper.prod.SysProdSkuMapper;
import com.purchase.ml.security.JwtUtil;
import com.purchase.ml.service.prod.SysProdPicService;
import com.purchase.ml.service.prod.SysProdService;
import com.purchase.ml.service.prod.SysProdSkuService;
import com.purchase.ml.service.shoppingcart.SysShoppingCartService;
import com.purchase.ml.utils.ShoppingCartUtils;
import io.netty.util.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.jwt.Jwt;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by kyyang on 2021/2/28 13:48
 */
@Service
@Slf4j
public class SysShoppingCartServiceImpl implements SysShoppingCartService {

    @Autowired
    private CacheDao cacheDao;

    @Autowired
    private SysProdPicService sysProdPicService;

    @Autowired
    private SysProdService sysProdService;

    @Autowired
    private SysProdSkuService sysProdSkuService;

    @Autowired
    private SysProdSkuMapper sysProdSkuMapper;

    @Autowired
    private SysDealerMapper sysDealerMapper;

    @Autowired
    private DealerProductMapper dealerProductMapper;

    @Override
    public void addProduct2Cart(ProductCartReq productCartReq) {
        String cartKey = ShoppingCartUtils.getCurShoppingCartKey();
        Map value = cacheDao.hget(RedisCacheEnum.REDIS_SHOPPING_CART_CACHE.getCode(),cartKey,Map.class);
        Map<Long,Integer> map = new HashMap<>();
        if(MapUtils.isNotEmpty(value)){
            map = value;
        }
        map.put(productCartReq.getProductId(),productCartReq.getQuantity());
        cacheDao.hset(RedisCacheEnum.REDIS_SHOPPING_CART_CACHE.getCode(),cartKey,map);
    }

    @Override
    public void delProduct2Cart(ProductCartReq productCartReq) {
        String cartKey = ShoppingCartUtils.getCurShoppingCartKey();
        Map value = cacheDao.hget(RedisCacheEnum.REDIS_SHOPPING_CART_CACHE.getCode(),cartKey,Map.class);
        Map<String,Integer> map = new HashMap<>();
        if(MapUtils.isNotEmpty(value)){
            map = value;
        }
        if(map.containsKey(productCartReq.getProductId().toString())){
            map.remove(productCartReq.getProductId().toString());
            cacheDao.hset(RedisCacheEnum.REDIS_SHOPPING_CART_CACHE.getCode(),cartKey,map);
        }else {
            log.warn("当前用户购物车:[{}] 商品不存在",productCartReq.getProductId());
        }
    }

    @Override
    public void clearCart() {
        String cartKey = ShoppingCartUtils.getCurShoppingCartKey();
        Map value = cacheDao.hget(RedisCacheEnum.REDIS_SHOPPING_CART_CACHE.getCode(),cartKey,Map.class);
        Map<Long,Integer> map = new HashMap<>();
        if(MapUtils.isNotEmpty(value)){
            map = value;
        }
        map.clear();
        cacheDao.hset(RedisCacheEnum.REDIS_SHOPPING_CART_CACHE.getCode(),cartKey,map);
    }

    @Override
    public void modifyProduct2Cart(ProductCartReq productCartReq) {
        //根据用户类型决定最小修改数量
        SysUser sysUser = JwtUtil.getCurrentUser();
        if(sysUser.getRoleType().equals(CommonConsts.ROLETYPE_MASTER)){
            //查询系统最小起购数量
            SysProductSku sysProductSku = sysProdSkuMapper.selectProductSkuByProductId(productCartReq.getProductId());
            if(sysProductSku.getMoq() > productCartReq.getQuantity() ){
                throw new BizException(CommonEnum.ILLEGAL_QULITY);
            }
        }else{
            //经销商
            SysDealer sysDealer = sysDealerMapper.selectByDealerId(sysUser.getDealerId());
            //查询上级最小起购量
            SysDealerPruduct sysDealerPruduct = dealerProductMapper.findBuyerProductByDealerId(sysDealer.getSuperior(),productCartReq.getProductId());
            if(sysDealerPruduct.getMoq() > productCartReq.getQuantity() ){
                throw new BizException(CommonEnum.ILLEGAL_QULITY);
            }
        }
        String cartKey = ShoppingCartUtils.getCurShoppingCartKey();
        Map value = cacheDao.hget(RedisCacheEnum.REDIS_SHOPPING_CART_CACHE.getCode(),cartKey,Map.class);
        Map<String,Integer> map = new HashMap<>();
        if(MapUtils.isNotEmpty(value)){
            map = value;
        }
        if(productCartReq.getQuantity()== 0){
            map.remove(productCartReq.getProductId());
        }else{
            map.put(String.valueOf(productCartReq.getProductId()),productCartReq.getQuantity());
        }
        log.info("productCartReq====={}",cartKey);
        log.info("map====={}",map);
        cacheDao.hset(RedisCacheEnum.REDIS_SHOPPING_CART_CACHE.getCode(),cartKey,map);
    }

    @Override
    public List<ShoppingCartRes> queryProduct2Cart() {
        String cartKey = ShoppingCartUtils.getCurShoppingCartKey();
        Map value = cacheDao.hget(RedisCacheEnum.REDIS_SHOPPING_CART_CACHE.getCode(),cartKey,Map.class);
        Map<String,Integer> map;
        if(MapUtils.isNotEmpty(value)){
            map = value;
        }else {
            return Collections.emptyList();
        }

        List<ShoppingCartRes> collect = map.entrySet().stream().filter(e->e.getValue()>0).map(e ->
        {
            ShoppingCartRes shoppingCartRes = new ShoppingCartRes();
            shoppingCartRes.setProductId(Long.valueOf(e.getKey()));
            shoppingCartRes.setQuantity(e.getValue());

            SysProduct sysProduct = sysProdService.findProductByProductId(Long.valueOf(e.getKey()));
            if(sysProduct == null){
                return null;
            }
            shoppingCartRes.setProductName(sysProduct.getProductName());
            BigDecimal price = BigDecimal.ZERO;
            SysUser currentUser = JwtUtil.getCurrentUser();
            Integer roleType = currentUser.getRoleType();
            switch (roleType){
                case CommonConsts.ROLETYPE_MASTER:
                    price = sysProduct.getPriceMasterDealer();
                    //如果是主经销商；价格需要×度量单位
                    SysProductSku sku = sysProdSkuService.findProductSkuByProductId(sysProduct.getProductId());
                    price = new BigDecimal(sku.getExchangeNum()).multiply(price); //价格*兑换数量；
                    break;
                case CommonConsts.ROLETYPE_DEALER:
                    price = sysProduct.getPriceDealer();
                    break;
            }
            shoppingCartRes.setPrice(price);
            shoppingCartRes.setProductModel(sysProduct.getProductModel());
            List<SysProductPic> list = sysProdPicService.findProductPicByProductId(Long.valueOf(e.getKey()));
            if(list!=null && list.size()>0){
                shoppingCartRes.setPicUrl(list.get(0).getPicUrl());
            }
            return shoppingCartRes;
        }).collect(Collectors.toList());
        collect.removeIf(Objects::isNull);
        return collect;
    }

    @Override
    public void delProduct2CartByOrder(List<ProductCartReq> list) {
        String cartKey = ShoppingCartUtils.getCurShoppingCartKey();
        Map value = cacheDao.hget(RedisCacheEnum.REDIS_SHOPPING_CART_CACHE.getCode(),cartKey,Map.class);
        Map<Long,Integer> map = new HashMap<>();
        if(MapUtils.isNotEmpty(value)){
            map = value;
        }else {
            return ;
        }
        if(CollectionUtils.isNotEmpty(list)){
            for(ProductCartReq p:list){
                map.remove(p.getProductId());
            }
        }
    }
}
